<template>
  <a-layout class="layout">
    <!-- 顶部导航栏 -->
    <a-layout-header class="header">
      <div class="header-content">
        <div class="logo">
          <span class="logo-text">Zomiot</span>
          <span class="logo-subtitle">中联物联</span>
        </div>
        
        <div class="nav-container">
          <a-menu
              v-model:selectedKeys="selectedKeys"
              theme="dark"
              mode="horizontal"
            class="main-menu"
          >
            <a-menu-item key="1">
              <router-link to="/home">首页</router-link>
            </a-menu-item>
            <a-menu-item key="2">
              <router-link to="/service">服务与支持</router-link>
            </a-menu-item>
            <a-menu-item key="3">
              <router-link to="/solution">解决方案</router-link>
            </a-menu-item>
            <a-menu-item key="4">
              <router-link to="/platform">平台案例</router-link>
            </a-menu-item>
            <a-menu-item key="5">
              <router-link to="/about">关于我们</router-link>
            </a-menu-item>
          </a-menu>
          
          <!-- 未登录状态 -->
          <div class="auth-buttons" v-if="!isLoggedIn">
            <a-space :size="12">
              <a-button class="login-btn" @click="goToLogin">登录</a-button>
              <a-button class="register-btn" type="primary" @click="goToRegister">注册</a-button>
            </a-space>
          </div>
          
          <!-- 已登录状态 -->
          <div class="user-info" v-else>
            <a-space :size="12">
              <span class="username-display">
                <UserOutlined style="margin-right: 6px" />
                {{ displayName }}
              </span>
              <a-button class="logout-btn" @click="handleLogout">登出</a-button>
            </a-space>
          </div>
      </div>
      </div>
    </a-layout-header>

    <!-- 主内容区 -->
    <a-layout-content class="main-content">
      <RouterView />
    </a-layout-content>

    <!-- 页脚 -->
    <a-layout-footer class="footer">
      <div class="footer-content">
        <a-row :gutter="[48, 24]">
          <a-col :xs="24" :sm="24" :md="8">
            <div class="footer-section">
              <h3 class="footer-title">Zomiot 中联物联</h3>
              <p class="footer-desc">专注于物联网技术服务与工业互联网解决方案</p>
              <div class="footer-info">
                <p>📍 厦门市湖里区金钟路3号1706-2</p>
                <p>📞 18850044111</p>
                <p>📧 info@zomiot.com</p>
              </div>
            </div>
          </a-col>
          
          <a-col :xs="24" :sm="12" :md="8">
            <div class="footer-section">
              <h3 class="footer-title">服务范围</h3>
              <ul class="footer-links">
                <li>物联网技术服务</li>
                <li>物联网应用服务</li>
                <li>工业互联网数据服务</li>
                <li>软件开发与技术支持</li>
                <li>数据处理和存储服务</li>
              </ul>
            </div>
          </a-col>
          
          <a-col :xs="24" :sm="12" :md="8">
            <div class="footer-section">
              <h3 class="footer-title">快速链接</h3>
              <ul class="footer-links">
                <li><router-link to="/home">首页</router-link></li>
                <li><router-link to="/service">服务与支持</router-link></li>
                <li><router-link to="/solution">解决方案</router-link></li>
                <li><router-link to="/platform">平台案例</router-link></li>
                <li><router-link to="/about">关于我们</router-link></li>
              </ul>
            </div>
          </a-col>
        </a-row>
        
        <a-divider style="border-color: rgba(255, 255, 255, 0.2)" />
        
        <div class="footer-bottom">
          <p>© 2016-2025 厦门市中联物联有限公司 版权所有</p>
          <p class="footer-meta">成立于 2016年3月 · 专注物联网技术研发与服务</p>
        </div>
      </div>
    </a-layout-footer>

    <!-- AI 聊天助手 -->
    <div class="ai-chatbot">
      <!-- 聊天窗口 -->
      <transition name="chat-slide">
        <div v-show="chatVisible" class="chat-window">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="chat-header-content">
              <div class="chat-avatar">
                <img src="@/static/lianer2.png" alt="莲儿" class="avatar-img" />
              </div>
              <div class="chat-title">
                <div class="chat-title-text">AI 小助手 莲儿</div>
                <div class="chat-subtitle">{{ isTyping ? '正在输入...' : '在线服务' }}</div>
              </div>
            </div>
            <CloseOutlined class="chat-close" @click="chatVisible = false" />
          </div>

          <!-- 聊天内容 -->
          <div class="chat-content" ref="chatContentRef">
            <div v-if="messages.length === 0" class="welcome-message">
              <img src="@/static/lianer.png" alt="莲儿" class="welcome-icon" />
              <h3>你好！我是 Zomiot 智能助手 莲儿</h3>
              <p>有什么可以帮助您的吗？</p>
              <div class="quick-questions">
                <div 
                  v-for="(q, index) in quickQuestions" 
                  :key="index" 
                  class="quick-question"
                  @click="sendQuickQuestion(q)"
                >
                  {{ q }}
                </div>
              </div>
            </div>

            <!-- 消息列表 -->
            <div v-for="(msg, index) in messages" :key="index" class="message-wrapper">
              <div :class="['message', msg.type]">
                <div class="message-avatar">
                  <UserOutlined v-if="msg.type === 'user'" />
                  <img v-else src="@/static/lianer2.png" alt="莲儿" class="avatar-img" />
                </div>
                <div class="message-content">
                  <div class="message-text" v-html="formatMessage(msg.content)"></div>
                  <div class="message-time">{{ msg.time }}</div>
                </div>
              </div>
            </div>

            <!-- 加载动画 -->
            <div v-if="isLoading" class="message bot">
              <div class="message-avatar">
                <img src="@/static/lianer2.png" alt="莲儿" class="avatar-img" />
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入框 -->
          <div class="chat-input-wrapper">
            <a-textarea
              v-model:value="inputMessage"
              :placeholder="isTyping ? '请等待回复...' : '输入您的问题...'"
              :auto-size="{ minRows: 1, maxRows: 4 }"
              :disabled="isTyping"
              @pressEnter="handleSendMessage"
              class="chat-input"
            />
            <a-button 
              type="primary" 
              :loading="isTyping"
              :disabled="!inputMessage.trim() || isTyping"
              @click="sendMessage"
              class="send-button"
            >
              <SendOutlined v-if="!isTyping" />
            </a-button>
          </div>
        </div>
      </transition>

      <!-- 悬浮按钮 -->
      <div 
        class="chat-float-button" 
        @click="toggleChat"
        :class="{ 'chat-open': chatVisible }"
      >
        <transition name="icon-fade" mode="out-in">
          <RobotOutlined v-if="!chatVisible" :key="'robot'"  class="float-icon" />
          <CloseOutlined v-else :key="'close'" class="float-icon" />
        </transition>
        <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>
      </div>
    </div>
  </a-layout>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { UserOutlined, RobotOutlined, CloseOutlined, SendOutlined } from '@ant-design/icons-vue';
import { logoutApi } from './api/auth.js';
import { askApi } from './api/ai.js';

const selectedKeys = ref(['1']);
const router = useRouter();
const isLoggedIn = ref(false);
const displayName = ref('');
const username = ref('');

// AI 聊天机器人相关状态
const chatVisible = ref(false);
const inputMessage = ref('');
const messages = ref([]);
const isTyping = ref(false);
const isLoading = ref(false);
const unreadCount = ref(0);
const chatContentRef = ref(null);

// 快速问题
const quickQuestions = ref([
  '你们公司做什么的？',
  '有哪些产品和服务？',
  '如何联系客服？'
]);

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token');
  const storedUsername = localStorage.getItem('username') || sessionStorage.getItem('username');
  const storedDisplayName = localStorage.getItem('displayName') || sessionStorage.getItem('displayName');

  console.log(token, storedUsername, storedDisplayName)
  
  if (token && storedUsername && storedDisplayName) {
    isLoggedIn.value = true;
    displayName.value = storedDisplayName;
    username.value = storedUsername;
  } else {
    isLoggedIn.value = false;
    displayName.value = '';
    username.value = '';
  }
};

// 组件挂载时检查登录状态
onMounted(() => {
  checkLoginStatus();
  
  // 监听storage变化（用于多标签页同步）
  window.addEventListener('storage', checkLoginStatus);
  
  // 监听自定义登录事件
  window.addEventListener('userLogin', checkLoginStatus);
});

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register');
};

// 处理登出
const handleLogout = async () => {
  try {
    // 调用后端登出接口
    await logoutApi();
    
    // 清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('displayName');
    sessionStorage.removeItem('token');
    sessionStorage.removeItem('username');
    sessionStorage.removeItem('displayName');
    // 更新登录状态
    isLoggedIn.value = false;
    username.value = '';
    displayName.value = '';
    message.success('登出成功！');
    
    // 跳转到首页
    router.push('/home');
  } catch (error) {
    console.error('登出失败:', error);
    
    // 即使接口调用失败，也清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('displayName');
    sessionStorage.removeItem('token');
    sessionStorage.removeItem('username');
    sessionStorage.removeItem('displayName');
    isLoggedIn.value = false;
    username.value = '';
    displayName.value = '';
    message.warning('登出成功');
    router.push('/home');
  }
};

// ==================== AI 聊天机器人功能 ====================

// 切换聊天窗口显示
const toggleChat = () => {
  chatVisible.value = !chatVisible.value;
  if (chatVisible.value) {
    unreadCount.value = 0;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 格式化消息（支持换行）
const formatMessage = (text) => {
  return text.replace(/\n/g, '<br>');
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight;
    }
  });
};

// 发送快速问题
const sendQuickQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

// 处理按下 Enter 发送消息
const handleSendMessage = (e) => {
  if (e.shiftKey) {
    // Shift+Enter 换行，不发送
    return;
  }
  e.preventDefault();
  sendMessage();
};

// 发送消息
const sendMessage = async () => {
  const question = inputMessage.value.trim();
  if (!question || isTyping.value) {
    return;
  }

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: question,
    time: getCurrentTime()
  });

  inputMessage.value = '';
  isTyping.value = true;
  isLoading.value = true;
  scrollToBottom();

  try {
    // 获取 token
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    
    // 构建请求头
    const headers = {
      'Content-Type': 'application/json',
    };
    
    // 如果 token 存在，添加到请求头
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    // 使用 fetch 实现 SSE POST 请求（通过 Vite 代理避免跨域）
    const response = await fetch('/api/ai/ask', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify({ question })
    });

    if (!response.ok) {
      throw new Error('网络请求失败');
    }

    // 添加 AI 消息占位符
    const aiMessageIndex = messages.value.length;
    messages.value.push({
      type: 'bot',
      content: '',
      time: getCurrentTime()
    });

    isLoading.value = false;
    scrollToBottom();

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        break;
      }

      // 解码数据
      buffer += decoder.decode(value, { stream: true });
      
      // 处理 SSE 格式的数据（event: 和 data: 开头）
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留最后不完整的行

      for (const line of lines) {
        if (line.startsWith('data:')) {
          // 提取 data: 后面的内容（不 trim，保留原始空格）
          const data = line.substring(5);
          
          // 跳过特殊标记
          if (data === '[DONE]') {
            continue;
          }
          
          // 直接追加内容到消息
          messages.value[aiMessageIndex].content += data;
          scrollToBottom();
        }
      }
    }

    // 如果聊天窗口未打开，增加未读消息数
    if (!chatVisible.value) {
      unreadCount.value++;
    }

  } catch (error) {
    console.error('发送消息失败:', error);
    message.error('发送失败，请稍后重试');
    
    // 添加错误消息
    messages.value.push({
      type: 'bot',
      content: '抱歉，我暂时无法回复。请稍后再试。',
      time: getCurrentTime()
    });
  } finally {
    isTyping.value = false;
    isLoading.value = false;
    scrollToBottom();
  }
};
</script>

<style scoped>
/* 全局布局 */
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* ==================== 顶部导航栏样式 ==================== */
.header {
  position: sticky;
  top: 0;
  z-index: 999;
  width: 100%;
  background: linear-gradient(135deg, #001529 0%, #002140 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 0;
  height: 64px;
  line-height: 64px;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

/* Logo 样式 */
.logo {
  display: flex;
  align-items: baseline;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.logo:hover {
  transform: translateY(-2px);
}

.logo-text {
  font-size: 24px;
  font-weight: 700;
  color: #fff;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #1890ff 0%, #52c41a 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.logo-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.65);
  font-weight: 400;
}

/* 导航容器 */
.nav-container {
  display: flex;
  align-items: center;
  gap: 32px;
  flex: 1;
  justify-content: flex-end;
}

/* 菜单样式 */
.main-menu {
  background: transparent;
  border: none;
  line-height: 64px;
}

:deep(.main-menu .ant-menu-item) {
  color: rgba(255, 255, 255, 0.85);
  font-size: 15px;
  font-weight: 500;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
  margin: 0 4px;
}

:deep(.main-menu .ant-menu-item:hover) {
  color: #fff;
  border-bottom-color: #1890ff;
}

:deep(.main-menu .ant-menu-item-selected) {
  color: #fff !important;
  background: rgba(24, 144, 255, 0.1) !important;
  border-bottom-color: #1890ff;
}

:deep(.main-menu .ant-menu-item a) {
  color: inherit;
  text-decoration: none;
}

/* 认证按钮 */
.auth-buttons {
  margin-left: 24px;
}

.login-btn {
  border-color: rgba(255, 255, 255, 0.3);
  color: #fff;
  background: transparent;
  transition: all 0.3s ease;
}

.login-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
}

.register-btn {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

/* 用户信息 */
.user-info {
  margin-left: 24px;
}

.username-display {
  height: 60px;
  color: #fff;
  font-size: 15px;
  font-weight: 500;
  padding: 6px 16px;
  background: rgba(24, 144, 255, 0.15);
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
  transition: all 0.3s ease;
}

.username-display:hover {
  background: rgba(24, 144, 255, 0.25);
}

.logout-btn {
  border-color: rgba(255, 107, 104, 0.5);
  color: #ff6b68;
  background: transparent;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  border-color: #ff4d4f;
  color: #fff;
  background: #ff4d4f;
}

/* ==================== 主内容区样式 ==================== */
.main-content {
  flex: 1;
  padding: 24px 50px;
  margin: 0;
  background: #f0f2f5;
}

/* ==================== 页脚样式 ==================== */
.footer {
  background: linear-gradient(135deg, #001529 0%, #002140 100%);
  color: rgba(255, 255, 255, 0.85);
  padding: 48px 24px 24px;
  margin-top: auto;
}

.footer-content {
  max-width: 1400px;
  margin: 0 auto;
}

.footer-section {
  margin-bottom: 24px;
}

.footer-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  position: relative;
  padding-bottom: 12px;
}

.footer-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, #1890ff, #52c41a);
  border-radius: 2px;
}

.footer-desc {
  color: rgba(255, 255, 255, 0.65);
  line-height: 1.8;
  margin-bottom: 16px;
}

.footer-info p {
  color: rgba(255, 255, 255, 0.75);
  line-height: 2;
  margin: 8px 0;
  transition: all 0.3s ease;
}

.footer-info p:hover {
  color: #1890ff;
  transform: translateX(4px);
}

.footer-links {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-links li {
  margin: 12px 0;
  color: rgba(255, 255, 255, 0.75);
  transition: all 0.3s ease;
  cursor: pointer;
}

.footer-links li:hover {
  color: #1890ff;
  transform: translateX(4px);
}

.footer-links a {
  color: inherit;
  text-decoration: none;
}

.footer-bottom {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
}

.footer-bottom p {
  color: rgba(255, 255, 255, 0.65);
  margin: 8px 0;
  font-size: 14px;
}

.footer-meta {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.45);
}

/* ==================== 响应式设计 ==================== */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 12px 16px;
  }
  
  .logo {
    margin-bottom: 12px;
  }
  
  .nav-container {
    flex-direction: column;
    gap: 16px;
    width: 100%;
  }
  
  .main-menu {
    width: 100%;
  }
  
  .auth-buttons {
    margin-left: 0;
  }
  
  .footer-title {
    font-size: 16px;
  }
}

/* ==================== 滚动条美化 ==================== */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: #f1f1f1;
}

:deep(::-webkit-scrollbar-thumb) {
  background: #888;
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: #555;
}


/* ==================== AI 聊天机器人样式 ==================== */
.ai-chatbot {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 1000;
}

/* 聊天窗口 */
.chat-window {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 380px;
  height: 500px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform-origin: bottom right;
}

/* 聊天窗口动画 */
.chat-slide-enter-active,
.chat-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-slide-enter-from,
.chat-slide-leave-to {
  opacity: 0;
  transform: scale(0.8) translateY(20px);
}

/* 聊天头部 */
.chat-header {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: #fff;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.chat-avatar .avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-font-smoothing: subpixel-antialiased;
}

.chat-title {
  display: flex;
  flex-direction: column;
}

.chat-title-text {
  font-size: 16px;
  font-weight: 600;
}

.chat-subtitle {
  font-size: 12px;
  opacity: 0.85;
  margin-top: 2px;
}

.chat-close {
  cursor: pointer;
  font-size: 16px;
  padding: 4px;
  transition: all 0.3s ease;
  border-radius: 4px;
}

.chat-close:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: rotate(90deg);
}

/* 聊天内容区 */
.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

/* 欢迎消息 */
.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.welcome-icon {
  width: 80px;
  height: 80px;
  font-size: 48px;
  color: #1890ff;
  margin-bottom: 16px;
  border-radius: 50%;
  object-fit: cover;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-font-smoothing: subpixel-antialiased;
}

.welcome-message h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.welcome-message p {
  font-size: 14px;
  color: #999;
  margin-bottom: 24px;
}

/* 快速问题 */
.quick-questions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 20px;
}

.quick-question {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 12px 16px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: left;
}

.quick-question:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #f0f7ff;
  transform: translateX(4px);
}

/* 消息 */
.message-wrapper {
  margin-bottom: 16px;
}

.message {
  display: flex;
  gap: 12px;
  animation: messageSlideIn 0.3s ease;
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
}

.message-avatar .avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  image-rendering: -webkit-optimize-contrast;/* WebKit 浏览器优化对比度 */
  image-rendering: crisp-edges;/* 保持边缘锐利 */
  backface-visibility: hidden;/* 隐藏背面 */
  -webkit-backface-visibility: hidden;/* WebKit 浏览器隐藏背面 */
  transform: translateZ(0); /* 启用硬件加速 */
  -webkit-font-smoothing: subpixel-antialiased;/* 亚像素抗锯齿 */
}

.message.user .message-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.message.bot .message-avatar {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: #fff;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message.user .message-content {
  align-items: flex-end;
}

.message-text {
  background: #fff;
  padding: 10px 14px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  word-wrap: break-word;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message.user .message-text {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: #fff;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  padding: 0 4px;
}

/* 输入中动画 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #1890ff;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 输入框区域 */
.chat-input-wrapper {
  padding: 16px;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.chat-input {
  flex: 1;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
}

.chat-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.send-button {
  height: 36px;
  border-radius: 8px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
}

.send-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

/* 悬浮按钮 */
.chat-float-button {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border-radius: 50%;
  box-shadow: 0 4px 16px rgba(24, 144, 255, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  color: #fff;
  font-size: 28px;
}

.chat-float-button:hover {
  transform: scale(1.1) rotate(5deg);
  box-shadow: 0 6px 24px rgba(24, 144, 255, 0.5);
}

.chat-float-button.chat-open {
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
  box-shadow: 0 4px 16px rgba(255, 77, 79, 0.4);
}

.chat-float-button.chat-open:hover {
  box-shadow: 0 6px 24px rgba(255, 77, 79, 0.5);
}

.float-icon {
  font-size: 28px;
}

.chat-float-button img.float-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

/* 图标切换动画 */
.icon-fade-enter-active,
.icon-fade-leave-active {
  transition: all 0.2s ease;
}

.icon-fade-enter-from {
  opacity: 0;
  transform: scale(0.5) rotate(-180deg);
}

.icon-fade-leave-to {
  opacity: 0;
  transform: scale(0.5) rotate(180deg);
}

/* 未读消息徽章 */
.unread-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  min-width: 20px;
  height: 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6px;
  border: 2px solid #fff;
  animation: bounce 0.6s ease infinite alternate;
}

@keyframes bounce {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-4px);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .chat-window {
    width: calc(100vw - 32px);
    height: calc(100vh - 120px);
    bottom: 76px;
    right: 16px;
  }

  .ai-chatbot {
    bottom: 16px;
    right: 16px;
  }

  .chat-float-button {
    width: 56px;
    height: 56px;
  }

  .float-icon {
    font-size: 24px;
  }
}

/* 聊天内容滚动条美化 */
.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track {
  background: transparent;
}

.chat-content::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}
</style>
